import time
import datetime
import json
import logging


class Order(object):
    def __init__(self, **kwargs):
        self.type = kwargs.pop('type', None)
        self.amount = kwargs.pop('amount', None)
        self.fund_channel = kwargs.pop('fund_channel', None)
        self.currency = kwargs.pop('currency', None)
        self.payment_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        self.description = kwargs.pop('description', None)
        self.notify_info = kwargs.pop('notify_info', {})
        self.trade_code = kwargs.pop('trade_code')

    def to_dict(self):
        return self.__dict__


class FundInOrder(Order):
    def __init__(self, **kwargs):
        kwargs.update({
            'type': 'fundin'
        })
        Order.__init__(self, **kwargs)

    def sign_value(self):
        return '{}|{}|{}|{}|{}'.format(
            self.type,
            self.fund_channel,
            self.amount,
            self.currency,
            self.payment_time
        )


class BasePaymentService:
    pass

    def __init__(self, merchant_id, password, host_url):
        self.merchant_id = merchant_id
        self.password = password
        self.host_url = host_url

        self.logger = logging.getLogger('vso.payment_service')

    def _sign(self, order):
        import hashlib
        md5 = hashlib.md5()

        sign_value = '{}{}{}'.format(self.password, order.sign_value(), order.payment_time)

        self.logger.info('Order sign , sign value {}'.format(sign_value))
        md5.update(sign_value.encode())
        return md5.hexdigest()

    def _request(self, url, data={}):
        import requests
        # json_data = json.dumps(data)
        self.logger.info('Request payment service , data '.format(data))
        res = requests.post('{}/{}'.format(self.host_url, url)
                            , json=data)
        self.logger.info('Request payment service finish , response code : '.format(res.status_code))
        if res.status_code == 200:
            return res.json()

    def fundin(self, order):
        self.logger.debug('Begin fundin payment')
        # 1. 构建订单map

        sign = self._sign(order)
        order = {
            'amount': float(order.amount),
            'fund_channel': order.fund_channel.id,
            'payment_time': order.payment_time,
            'currency': order.currency,
            'merchant': self.merchant_id,
            'sign': sign,
            'desc': order.desc or '',
            # 'return_url': order.return_url,
        }
        # 2. 发送订单
        self.logger.info('Send fundin paymnet {}'.format(order))
        res = self._request('fundin', data=order)

        # 3  解析结果

        self.logger.info('Fundin paymnet result {}'.format(order))

        if res.success:
            pass

    def refund(self):
        pass
